package cn.edu.scut.sys.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.edu.scut.sys.service.UserService;
import cn.edu.scut.sys.utils.StringUtils;
import cn.edu.scut.sys.vo.User;


@Controller
@RequestMapping("/log")
public class LoginController {

	private UserService userService;

	@Resource(name="userService")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping("/in")
	public String in(String name, String password, HttpServletRequest request){
		
		try{
			if (StringUtils.isEmpty(name)){
				request.setAttribute("msg", "用户名或密码错误！");
				return "/login";
			}
			
			if (StringUtils.isEmpty(password)){
				request.setAttribute("msg", "用户名或密码错误！");
				return "/login";
			}
			
			User user = userService.getUserByName(name);
			if (null == user) {
				request.setAttribute("msg", "用户名或密码错误！");
				return "/login";
			}
			
			if (toMd5(password).equals(user.getPassword())) {
				request.getSession().setAttribute("sys_user", user);
				return "redirect:/page/shootScoreList.jsp";
			} else {
				request.setAttribute("msg", "用户名或密码错误！");
				return "/login";
			}
			
		}catch(Exception ex){
			request.setAttribute("msg", "系统错误！");
			return "/login";
		}
		
	}
	
	@RequestMapping("/out")
	public String out(HttpSession session) {
		session.removeAttribute("sys_user");
		session.invalidate();
		return "redirect:/login.jsp";
	}
	
	public String toMd5(String s){
		byte[] bytes;
		bytes=s.getBytes();
		try{
			MessageDigest al=MessageDigest.getInstance("MD5");
			al.reset();
			al.update(bytes);
			return toHexString(al.digest(),"");
		}
		catch(NoSuchAlgorithmException e){
			
		}
		return null;

	}
	
	private String toHexString (byte[] bytes, String separator){
		StringBuilder hexString =new StringBuilder();
		for (byte b:bytes){
				String hex=Integer.toHexString(0xFF & b);
				if(hex.length()==1){
					hexString.append('0');
				}
				hexString.append(hex).append(separator);
		}
	return hexString.toString();
	}
	
}
